// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/exec/utils/port_util.h>
#include <turbo/log/logging.h>
#include <gtest/gtest.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pollux/common/base/exceptions.h>

namespace kumo::pollux::exec::test {

// Try binding to port. Return false if it couldn't.
bool tryBind(int port) {
  int sock = socket(PF_INET, SOCK_STREAM, 0);
  POLLUX_CHECK_NE(sock, -1, "Error while creating socket: {}", errno);

  sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = port;
  addr.sin_addr.s_addr = INADDR_ANY;

  int result = ::bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr));
  return result != -1;
}

TEST(PortUtilTest, ensureAvailablePort) {
  const size_t trials = 100;
  const size_t retries = 5;

  for (size_t i = 0; i < trials; i++) {
    // Since there might be a race condition between fetching the port and
    // binding to it, try it `retries` times on each iteration.
    bool trialSucceeded = false;

    for (size_t j = 0; j < retries; j++) {
      auto port = getFreePort();
      if (tryBind(port)) {
        trialSucceeded = true;
        break;
      }
    }

    EXPECT_TRUE(trialSucceeded)
        << "Trial run #" << i << " was not able to bind to returned port after "
        << retries << " retries.";
  }
}

TEST(PortUtilTest, uniquePorts) {
  const size_t trials = 100;
  const size_t numPorts = 100;

  for (size_t i = 0; i < trials; i++) {
    auto ports = getFreePorts(numPorts);
    std::unordered_set<int> set(ports.begin(), ports.end());
    EXPECT_EQ(set.size(), numPorts)
        << "getFreePorts() returned non-unique ports.";
  }
}

} // namespace kumo::pollux::exec::test
